package com.an.nettyl;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class ServerHandler  extends SimpleChannelInboundHandler<ByteBuf> {
 
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("客户端加入");
		ctx.channel().writeAndFlush("hello client!!".getBytes(CharsetUtil.UTF_8));
		System.out.println("客户端加入,fasongshujuwanbi ");
	}
    //每当从客户端收到新的数据时，这个方法会在收到消息时被调用
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
 
        ByteBuf in = (ByteBuf) msg;
        try {
            // Do something with msg
            System.out.println("server get :" + in.toString(CharsetUtil.UTF_8));
 
            ChannelFuture channelFuture = ctx.writeAndFlush(Unpooled.copiedBuffer(("server send time: " + new Date()).getBytes()));
 
            //服务端发送数据完毕后,关闭通道
            channelFuture.addListener(ChannelFutureListener.CLOSE);
 
        } finally {
            //ByteBuf是一个引用计数对象，这个对象必须显示地调用release()方法来释放
            //or ((ByteBuf)msg).release();
            ReferenceCountUtil.release(msg);
        }
 
    }
 
    //exceptionCaught()事件处理方法是当出现Throwable对象才会被调用
    //当Netty由于IO错误或者处理器在处理事件时抛出的异常时
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
 
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
 
    }
 
}
